package com.neusoft.neu24.service.impl;



import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.neusoft.neu24.entity.Member;
import com.neusoft.neu24.entity.User;
import com.neusoft.neu24.mapper.UserMapper;
import com.neusoft.neu24.result.Result;
import com.neusoft.neu24.service.UserService;
import com.neusoft.neu24.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserServiceimpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Member findByUser(String uname) {
        Member u = userMapper.findByUser(uname);
        return u;
    }

    @Override
    public void register(String uname, String psw,String tel,String gender) {
        userMapper.add(uname,psw,tel,gender);
    }

    @Override
    public Result findUserByToken(String token) {
        if(StringUtils.isBlank(token)){
            return Result.error("token不合法");
        }
        Map<String, Object> stringObjectMap = JwtUtil.checkToken(token);
        if(stringObjectMap == null){
            return Result.error("token不合法");
        }
        String userJson = redisTemplate.opsForValue().get("token" + token);
        if(StringUtils.isBlank(userJson)){
            return Result.error("token已过期");
        }
        User user = JSON.parseObject(userJson, User.class);
        return Result.success(user);
    }
}
